package com.onlinelearn.content.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.onlinelearn.content.mapper.CourseCategoryMapper;
import com.onlinelearn.content.model.dto.CourseCategoryTreeDto;
import com.onlinelearn.content.model.po.CourseCategory;
import com.onlinelearn.content.service.CourseCategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 课程分类 服务实现类
 * </p>
 *
 * @author itcast
 */
@Slf4j
@Service
public class CourseCategoryServiceImpl extends ServiceImpl<CourseCategoryMapper, CourseCategory> implements CourseCategoryService {

    @Autowired
    CourseCategoryMapper mapper;
    @Override
    public List<CourseCategoryTreeDto> selectTreeNodes(String id) {
        List<CourseCategoryTreeDto> list = mapper.selectTreeNodes(id);
        List<CourseCategoryTreeDto> courseCategoryTreeDtos = new ArrayList<>();
        Map<String,CourseCategoryTreeDto> map = new HashMap<>();
        list.stream().forEach(item -> {
//          将根节点下面的数据封装，并且下级的下级也需要封装
            map.put(item.getId(),item);
            if(item.getParentid().equals(id)){
                courseCategoryTreeDtos.add(item);
            }
            CourseCategoryTreeDto courseCategoryTreeDto = map.get(item.getParentid());
            if(courseCategoryTreeDto != null){
                if(courseCategoryTreeDto.getChildrenTreeNodes() == null){
                    courseCategoryTreeDto.setChildrenTreeNodes(new ArrayList<>());
                }
                courseCategoryTreeDto.getChildrenTreeNodes().add(item);
            }
        });
        return courseCategoryTreeDtos;
    }
}
